<?php
$auth = Auth::getAuth('current_user');
$db = new Database();
$fs = new functions();
$userCompany = new userQueries();
$upload = new upload();
$timezone = "Asia/Manila";
if(function_exists('date_default_timezone_set')) date_default_timezone_set($timezone);

    if(isset($_POST['action'])){
        $action = $_POST['action'];
        $date = $fs->currentDateTime();
            
            if($action=="insertTask"){
                $task_date_created = $_POST['task_date_created'];
                $task_date_closed = $_POST['task_date_created'];
                $task_project = $_POST['task_project'];
                $task_name = $_POST['task_name'];
                $task_description = $_POST['task_description'];
                $task_team = $_POST['task_team'];
                $task_status = $_POST['task_status'];
                $task_due_date = $_POST['task_due_date'];
                $task_remarks = $_POST['task_remarks'];
                $task_editos = $_POST['task_editos'];
                $task_viewers = $_POST['task_viewers'];
                
                $insert = array("project_title"         =>      $task_project,
                                "task"                  =>      $task_name,
                                "description"           =>      $task_description,
                                "member"                =>      $task_team,
                                "status"                =>      $task_status,
                                "due_date"              =>      $task_due_date,
                                "date_created"          =>      $task_date_created,
                                "date_closed"           =>      $task_date_closed,
                                "remarks"               =>      $task_remarks,
                                "createdBy"             =>      $auth['id'],
                                "Editors"               =>      $task_editos,
                                "Viewers"               =>      $task_viewers,
                                "date"                  =>      $date,
                                "is_active"             =>      1);
                                
                                $taskID = $db->insert("tbtasks",$insert);
                                
                                notifications::taskNotification("","tbtasks",$auth,$taskID,$task_team,$task_viewers,$task_editos);
                $images = $_POST['imagesGet'];
                $decode_img = json_decode($images,true);
                                
                                // Create folder for the postImage
                                $folder_name = $_POST['folder_location'];
                                $path = "images/" . $folder_name;
                                $id_encrypt = md5(md5($taskID));
                                $dir = $path."/".$id_encrypt;
                                if(count($decode_img)!=0){  
                                    $upload->createFolder($dir);
                                }
                                    // Move files to the directory
                                    $copy_foldername = md5(md5($auth['id']));
                                    $from = "images/" . $folder_name . "/temporaray_files/".$copy_foldername;
                                    $postFiles = $upload->getAllfiles_fromDirectory($from);
                                        $ext_file = array();
                                        $ext_img = array();
                                            foreach($decode_img as $img){
                                                copy($from . '/' . $img, $dir . '/' . $img);
                                                $extension = explode(".", $img);
                                                $last_ext = $extension[count($extension)-1];
                                                $valid_formats = unserialize(IMG_EXTENSION);
                                                
                                                    if(!in_array($last_ext,$valid_formats)){
                                                        array_push($ext_file,$last_ext);
                                                    }else{
                                                        array_push($ext_img,$last_ext);
                                                    }
                                            }
                                        $upload->unlinkRecursive($from, "");
                                        $tU = array();
                                        $tu_arr = array();
                                        $vu_arr = array();
                                        $eu_arr = array();
                                        $arr = array();
                                        $getTaskUser = $db->query("SELECT * FROM tbuser WHERE id IN ($task_team) AND is_active={$db->escape(1)}","array");
                                        foreach($getTaskUser as $TUser){
                                            $json_decode = Settings::noti_settings($TUser['id'],'notifications');
                                            $json_notifications = $json_decode[0]['notifications'];
                                            $json_noti = $json_notifications['Request'];
                                            
                                            if($json_noti[0]=="1"){
                                                $to = array($TUser['email']=>$TUser['first_name'] . " " . $TUser['last_name']);
                                                $name = $auth['first_name'] . " " . $auth['last_name'];
                                                $msg = "added you as a team in " . $task_project . "'s tasks";
                                                $f_name = $auth['first_name'];
                                                $img = $userCompany->avatarPic("tbuser",$auth['id'],"60","60","small","avatar",'style="float: left;border-radius:50px;margin-right: 5px;"');
                                                $tu_arr["Member"] = array($to);
                                                $type = "Task's";
                                                $t = "";
                                                $path = $fs->curPageURL('port') . "/task?view_type=view_task&taskID=" . $taskID;
                                                $mail = new Mail_Notification();
                                                $mail->set_notifications($to,$msg,$img,$auth['id'],$name,"Tasks",$f_name,$type,$t,$path);
                                                array_push($tU,$tu_arr);
                                            }
                                        }
                                            
                                        $getEditorUser = $db->query("SELECT * FROM tbuser WHERE id IN ($task_editos) AND is_active={$db->escape(1)}","array");
                                        foreach($getEditorUser as $EUser){
                                            $vu_arr["Editor"] = array($EUser['email']=>$EUser['first_name'] . " " . $EUser['last_name']);
                                            array_push($tU,$vu_arr);
                                        }
                                            
                                        $getViewerUser = $db->query("SELECT * FROM tbuser WHERE id IN ($task_viewers) AND is_active={$db->escape(1)}","array");
                                        foreach($getViewerUser as $VUser){
                                            $eu_arr["Viewer"] = array($VUser['email']=>$VUser['first_name'] . " " . $VUser['last_name']);
                                            array_push($tU,$eu_arr);
                                        }
                                        
                                            //echo $tU;
                                        
                                //echo var_dump($insert);
            }else if($action=="loadTask"){
                
                $getTasks = $db->query("SELECT *, t.date as taskDate, t.id as taskID FROM tbtasks t
                                       LEFT JOIN tbuser u on u.id=t.createdBy
                                       WHERE u.company_id={$db->escape($auth['company_id'])} AND t.is_active={$db->escape(1)} ORDER BY taskDate DESC","array");
                
                $encode_tasks = array();
                
                
                foreach($getTasks as $tasks){
                    $encode_membersName = array();
                    $encode_editorsName = array();
                    $encode_viewersName = array();
                    
                    
                    $getMember = $db->query("SELECT * FROM tbuser WHERE id IN (" . $tasks['member'] . ")","array");
                    foreach($getMember as $member){
                        $m = array("name"       =>      $member['first_name'] . " " . $member['last_name'],
                                   "id"         =>      $member['id']);
                        array_push($encode_membersName,$m);
                    }   
                    
                    $getEditors = $db->query("SELECT * FROM tbuser WHERE id IN (" . $tasks['Editors'] . ")","array");
                    foreach($getEditors as $editors){
                        $e = array("name"       =>      $editors['first_name'] . " " . $editors['last_name'],
                                   "id"         =>      $editors['id']);
                        array_push($encode_editorsName,$e);
                        
                        $eid[] = $editors['id'];
                        //$eid[] = $tasks['createdBy'];
                    }   
                    
                    $getViewers = $db->query("SELECT * FROM tbuser WHERE id IN (" . $tasks['Viewers'] . ")","array");
                    foreach($getViewers as $viewers){
                        $v = array("name"       =>      $viewers['first_name'] . " " . $viewers['last_name'],
                                   "id"         =>      $viewers['id']);
                        array_push($encode_viewersName,$v);
                    }   
                    
                    // Load folder for the message
		    $path = "images/taskUpload";
                    $id_encrypt = md5(md5($tasks['taskID']));
                    $dir = $path."/".$id_encrypt;
                    $postFiles = $upload->getAllfiles_fromDirectory($dir);
		    
			    $ext_file = array();
			    $ext_img = array();
                                foreach($postFiles as $img){
				    $extension = explode(".", $img);
				    $last_ext = $extension[count($extension)-1];
				    $valid_formats = unserialize(IMG_EXTENSION);
				    $path_resize_image = $dir . "/" . $img;
					if(!in_array($last_ext,$valid_formats)){
					    array_push($ext_file,$last_ext);
					}else{
					    array_push($ext_img,$last_ext);
					}
                                }
				
                    //
                        $encodePostImage = array("img"            =>  $postFiles,
                                                "postFolderName"     =>  $id_encrypt,
                                               "lengthImg"          => count($ext_img),
					       "extension_file"		    =>  $ext_file,
						    "extension_img"		    =>  $ext_img,
                                                    "image_resize"	=>	getimagesize($path_resize_image)
                                               );
                    
                    $encode_tasks = array("tID"              =>      $tasks['taskID'],
                                    "project_title"         =>      $tasks['project_title'],
                                    "task"                  =>      $tasks['task'],
                                    "description"           =>      $tasks['description'],
                                    "membersName"           =>      $encode_membersName,
                                    "member"                =>      $tasks['member'],
                                    "countMembers"          =>      count(explode(",",$tasks['member'])),
                                    "status"                =>      $tasks['status'],
                                    "due_date"              =>      $tasks['due_date'],
                                    "date_created"          =>      $tasks['date_created'],
                                    "date_closed"           =>      $tasks['date_closed'],
                                    "remarks"               =>      $tasks['remarks'],
                                    "createdBy"             =>      $tasks['createdBy'],
                                    "Editors"               =>      $tasks['Editors'],
                                    "editorsName"           =>      $encode_editorsName,
                                    "searchEditorsName"     =>      implode(",",$eid),
                                    "Viewers"               =>      $tasks['Viewers'],
                                    "viewersName"           =>      $encode_viewersName,
                                    "date"                  =>      $tasks['taskDate'],
                                    "createdByName"         =>      $tasks['first_name'] . " " . $tasks['last_name'],
                                    "authID"                =>      $auth['id'],
                                    "user_level"            =>      $auth['user_level_id'],
                                    "taskAttachment"        =>      $encodePostImage);
                    
                    
                    // Return
                    $arr[] = array("Tasks"            =>      $encode_tasks);
                }
                
                echo json_encode($arr);
                
            } elseif($action=="updateTask"){
                $task_date_created = $_POST['task_date_created'];
                $task_date_closed = $_POST['task_date_created'];
                $task_project = $_POST['task_project'];
                $task_name = $_POST['task_name'];
                $task_description = $_POST['task_description'];
                $task_team = $_POST['task_team'];
                $task_status = $_POST['task_status'];
                $task_due_date = $_POST['task_due_date'];
                $task_remarks = $_POST['task_remarks'];
                $task_editos = $_POST['task_editos'];
                $task_viewers = $_POST['task_viewers'];
                $task_createdBy = $_POST['createdBy'];
                $insert = array("project_title"         =>      $task_project,
                                "task"                  =>      $task_name,
                                "description"           =>      $task_description,
                                "member"                =>      $task_team,
                                "status"                =>      $task_status,
                                "due_date"              =>      $task_due_date,
                                "date_created"          =>      $task_date_created,
                                "date_closed"           =>      $task_date_closed,
                                "remarks"               =>      $task_remarks,
                                "createdBy"             =>      $task_createdBy,
                                "Editors"               =>      $task_editos,
                                "Viewers"               =>      $task_viewers,
                                "date"                  =>      $date,
                                "is_active"             =>      1);
                
                $task_taskID = $_POST['taskID'];
                                
                $condition = array("id"                 =>      $task_taskID);
                                $db->update("tbtasks",$insert,$condition);
                                
            } elseif($action=="deleteTask"){
                $dataID = $_POST['dataID'];
                
                $db->update("tbtasks",array("is_active" =>  0),array("id"   =>  $dataID));
            }
            
    }


?>